package org.biubiu0002.baiblog.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.biubiu0002.baiblog.common.constants.CacheConstants;
import org.biubiu0002.baiblog.common.utils.PageUtils;
import org.biubiu0002.baiblog.common.utils.Query;
import org.biubiu0002.baiblog.core.dao.LikeRecordDao;
import org.biubiu0002.baiblog.core.model.entity.LikeRecordEntity;
import org.biubiu0002.baiblog.core.service.LikeRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("likeRecordService")
public class LikeRecordServiceImpl extends ServiceImpl<LikeRecordDao, LikeRecordEntity> implements LikeRecordService {

    @Resource
    LikeRecordDao likeRecordDao;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<LikeRecordEntity> page = this.page(
                new Query<LikeRecordEntity>().getPage(params),
                new QueryWrapper<LikeRecordEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void syncShareLikeMapFromRedis2DB() {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(CacheConstants.getShareLikeMapKey());
        List<LikeRecordEntity> list = new ArrayList<>();
        entries.forEach((userShareField, isLike) -> {
            int like = Integer.parseInt((String) isLike);
            String[] split = ((String) userShareField).split(CacheConstants.SEPARATOR);
            String userUid = split[0];
            String shareId = split[1];
            //更新点赞记录
            LikeRecordEntity likeRecordEntity = new LikeRecordEntity();
            likeRecordEntity.setUserUid(userUid);
            likeRecordEntity.setShareId(shareId);
            likeRecordEntity.setLike(like == 1);
            list.add(likeRecordEntity);
        });
        List<List<LikeRecordEntity>> partition = Lists.partition(list, 1000);
        for (List<LikeRecordEntity> l : partition) {
            likeRecordDao.saveOrUpdateBatch(l);
        }
    }

    @Override
    public Boolean isUserLikeShare(String userUid, String shareId) {
        String s = (String) redisTemplate.opsForHash().get(CacheConstants.getShareLikeMapKey(), CacheConstants.getUserShareField(userUid, shareId));
        return CacheConstants.TRUE.equals(s);
    }

}